package com.chebaohui.iqs.sdk;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

/**
 * Java读写Property文件
 * 
 * @author xielonghai
 *
 */
public class PropertyUtils {
	/**
	 * springboot下读取配置文件,错误返回null
	 * 
	 * @param filePath
	 *            jar包同级目录下
	 * @param key
	 *            名称
	 * @return
	 */
	public static String readSpringboot(String filePath, String key) {
		Properties props = new Properties();
		try {
			FileReader f = new FileReader(new File(System.getProperty("user.dir") + File.separator + filePath));
			props.load(f);
			f.close();
			return props.getProperty(key);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * springboot下写入配置文件,错误返回false
	 * 
	 * @param filePath
	 *            jar包同级目录下
	 * @param key
	 *            名称
	 * @param value
	 *            修改值
	 * @return
	 */
	public static boolean writeSpringboot(String filePath, String key, String value) {
		if (null == value)
			return false;

		if (value.equals(readSpringboot(filePath, key)))
			return true;

		Properties prop = new Properties();
		try {
			File file = new File(System.getProperty("user.dir") + File.separator + filePath);
			if (!file.exists())
				file.createNewFile();
			InputStream fis = new FileInputStream(file);
			prop.load(fis);
			// 一定要在修改值之前关闭fis
			fis.close();
			OutputStream fos = new FileOutputStream(filePath);
			prop.setProperty(key, value);
			// 保存，并加入注释
			prop.store(fos, "Update '" + key + "' value");
			fos.close();

			if (value.equals(readSpringboot(filePath, key)))
				return true;
			else
				return false;
		} catch (IOException e) {
			// LogUtil.writeErrorLog("Visit " + filePath + " for updating " +
			// value + " value error");
			return false;
		}
	}
}
